<%@page import="com.solution.admin.order.constants.OrderConstants"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sl" tagdir="/WEB-INF/tags" %>
<%@page import="com.solution.common.config.PublicConfig"%>
<%@page import="com.solution.common.constants.PublicStatus"%>
<%@page import="com.solution.admin.home.constants.IndexConstants"%>
<%
	String basePath = PublicConfig.ROOT_PATH;
	String imgRootURL = PublicConfig.IMG_ROOT_URL;
%>	
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<title>支付平台</title>
<link rel="stylesheet" type="text/css" href="<%=basePath%>/statics_wx/css/style.css?20180113">
<script src="<%=basePath%>/statics_wx/js/jquery.min.js"></script>
<script src="<%=basePath%>/statics_wx/js/js.js"></script>
<script type="text/javascript" src="<%=basePath%>/statics/plugins/upload/ajaxfileupload.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript" src="<%=basePath%>/statics/plugins/layer/layer.js"></script>
<script type="text/javascript">
	//系统域名 
	var rootPath = '<%=basePath%>';
	// 系统上传文件展示域名
	var imgRootURL = '<%=imgRootURL%>';
</script>
<script>
	$(function(){
		
		var account_id = '';
		
		$('.bank_list11 dl dt').click(function(){
			account_id = $(this).find("#account_id").val();
			$(this).addClass('checked');
			$(this).siblings().removeClass('checked');
		});
	
		// 对公支付
		$('.zf_way1 ul li label').click(function(){
			if($(this).hasClass('checked')){
				$(this).addClass('checked');
				$(this).parent().addClass('checked');
				$(this).parent().siblings().find('label').removeClass('checked');
				$(this).parent().siblings().removeClass('checked');
				$('.zf_way3 ul li label').removeClass('checked');
				$(this).find('.bank_list11').show();
			}else{
				$(this).addClass('checked');
				$(this).parent().addClass('checked');
				$(this).parent().siblings().find('label').removeClass('checked');
				$(this).parent().siblings().removeClass('checked');
				$('.zf_way3 ul li label').removeClass('checked');
				$(this).find('.bank_list11').show();
				var tag = $(this).closest("li").find("a[tag='tag']").attr("name");
				location.href = "#"+tag;
			}
		});
        
		// 个人支付
		$('.zf_way3 ul li label').click(function(){
			if($(this).hasClass('checked')){
				$(this).addClass('checked');
				$('.zf_way1 ul li label').removeClass('checked');
				$('.zf_way1 ul li').removeClass('checked');
				$('.bank_list11').hide();
			}else{
				$(this).addClass('checked');
				$(this).parent().siblings().find('label').removeClass('checked');
				$('.zf_way1 ul li label').removeClass('checked');
				$('.zf_way1 ul li').removeClass('checked');
				$('.bank_list11').hide();
			}
		});
		
		//默认选择第一种支付方式
		$("label.checked").find("dl").find("dt").eq(0).addClass("checked");
		account_id = $("label.checked").find("dl").find("dt").eq(0).find("#account_id").val();
		
		// 确认支付
		$("#btn_pay").click(function(){
			var payType = $("label.checked").attr("pay_type");
			var url = "";
			var tag = "";
			if (payType == "02") {
				callPay();
				return false;
			} else if (payType == "03") {
				url = rootPath + "/wx/order/publicPay";
			} else if (payType == "04") {
				url = rootPath + "/wx/order/privatePay";
			}
			var accountId = account_id;
			var imgs = [];
			$("label[pay_type="+payType+"]").closest("li").find("img:gt(0)").each(function() {
				var imgSrc = $(this).attr("src").replace(imgRootURL,"");
				if(imgSrc) {
					imgs.push(imgSrc.split('?')[0]);
				}
			});
			console.log(payType);
			console.log(accountId);
			if ((payType == "03" || payType == "04") && (accountId == "" || accountId == undefined)) {
				layer.msg('请选择支付账户',{time:1000});
				return false;
			}
			if ((payType == "03" || payType == "04") && (imgs.length  == 0)) {
				layer.msg('请上传支付凭证',{time:1000});
				return false;
			}
			var form = $('<form></form>');  
			form.attr('action', url);  
			form.attr('method', 'post');
			form.attr('target', '_self');
			form.append("<input type='hidden' name='orderCode'  value='"+$("#order_code").val()+"'/>");
			form.append("<input type='hidden' name='accountId'  value='"+accountId+"'/>");
			form.append("<input type='hidden' name='imgPath'  value='"+imgs.join(",")+"'/>");
			form.appendTo("body");
			form.submit();
		});

		var btn_public_pay = $("#btn_public_pay");
		var btn_private_pay = $("#btn_private_pay");
		btn_public_pay.click(function(){
			$("#public_pay_upload").click();
		});
		btn_private_pay.click(function(){
			$("#private_pay_upload").click();
		});
		
		/*
		//微信图片上传,IOS有问题
		wx.config({
			debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			appId : $('#appId').val(), // 必填，公众号的唯一标识
			timestamp : $('#timestamp').val(), // 必填，生成签名的时间戳
			nonceStr : $('#nonceStr').val(), // 必填，生成签名的随机串
			signature : $('#signature').val(),// 必填，签名
			jsApiList : [ 'chooseImage', 'uploadImage' ] // 必填，需要使用的JS接口列表，所有JS接口列表
		});
		
		wx.ready(function(){
			btn_public_pay.on('click', function() {
				takePicture($(this),'public');
			});
			
			btn_private_pay.on('click', function() {
				takePicture($(this),'private');
			});
		});*/
	});
	
	

	function onBridgeReady() {
		var appId = $("#pay_appId").val();
		var timeStamp = $("#pay_timeStamp").val();
		var nonceStr = $("#pay_nonceStr").val();
		var packageStr = $("#pay_package").val();
		var paySign = $("#pay_paySign").val();
		var signType = $("#pay_signType").val();
		WeixinJSBridge.invoke('getBrandWCPayRequest', {
			"appId" : appId, //公众号名称，由商户传入     
			"timeStamp" : timeStamp, //时间戳，自1970年以来的秒数     
			"nonceStr" : nonceStr, //随机串     
			"package" : packageStr,
			"signType" : signType, //微信签名方式：     
			"paySign" : paySign //微信签名 
		}, function(res) {
			// 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
			if (res.err_msg == "get_brand_wcpay_request:ok") {
				layer.msg('支付成功，正跳转我的订单...',{time:1000});
				setTimeout(function(){
					window.location.href = rootPath+"/wx/order/list";
				},1000);
			} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
				layer.msg('用户已取消支付',{time:1000});
			} else if (res.err_msg == "get_brand_wcpay_request:fail") {
				alert(JSON.stringify(res));
				layer.msg('支付失败',{time:1000});
			}
		});
	}
	//支付
	function callPay(){
		if (typeof WeixinJSBridge == "undefined") {
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
				document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
			}
		} else {
			onBridgeReady();
		}
	}
	
	
	/**
	* 拍照
	*/
	function takePicture(this_,type){
		wx.chooseImage({
			count: 1, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {
				var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
				//判断ios是不是用的 wkwebview 内核
				if (window.__wxjs_is_wkwebview) {
					wx.getLocalImgData({ //循环调用  getLocalImgData
						localId : res.localIds, // 图片的localID
						success : function(res) {
							var localData = res.localData; //localData是图片的base64数据，可以用img标签显示
							//localData = localData.replace('jgp', 'jpeg');//iOS 系统里面得到的数据，类型为 image/jgp,因此需要替换一下
							localIds = localData; //把base64格式的图片添加到ioslocId数组里 这样该数组里的元素都是base64格式的
						},
						fail : function(res) {
							layer.msg('IOS上传图片失败，请重试', {
								time : 1000
							});
						}
					});
				}
				wx.uploadImage({
					localId : localIds.toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
					isShowProgressTips : 1, // 默认为1，显示进度提示
					success : function(res) {
						var mediaId = res.serverId; // 返回图片的服务器端ID，即mediaId
						//将获取到的 mediaId 传入后台 方法
						$.post(rootPath + "/wx/upload/picture", {
							mediaId : mediaId
						}, function(res) {
							if (res.resultCode == '1') {
								var img = "<div class=\"mypic\">" + "<img src=\"" + imgRootURL + res.filePath
										+ "?x-oss-process=image/resize,m_pad,h_60,w_60\" data-src=\"" + imgRootURL
										+ res.filePath + "\" onclick=\"imageView(this);\"/>"
										+ "<a href=\"javascript:void(0)\" class=\"icon_close\"></a>" + "</div>";
								this_.closest("div.upload_picpart").append($(img));
								this_.closest("div.upload_picpart").find("a.icon_close").each(function() {
									$(this).click(function() {
										$(this).closest("div.mypic").remove();
										countImage("btn_" + type + "_pay");
									});
								});
								countImage("btn_" + type + "_pay");
							} else {
								layer.msg(res.resultMsg, {
									time : 1000
								});
							}
						})
					},
					fail : function(res) {
						layer.msg('上传图片失败，请重试', {
							time : 1000
						});
					}
				});
			}
		});
	}

	//微信图片预览
	function imageView(this_) {
		var src = $(this_).attr("data-src");
		var srcPre = src + '?x-oss-process=image/resize,m_pad,h_60,w_60';
		/**
		wx.previewImage({
			current : srcPre, // 当前显示图片的http链接  
			urls : [ src ]
			// 需要预览的图片http链接列表  
		})
		*/
		WeixinJSBridge.invoke('imagePreview', {  
            'current': srcPre,  
            'urls': [src]
        });  
	}

	//图片计数
	function countImage(btn_id) {
		var imageNum = $("#" + btn_id).closest(".upload_picpart").find(".mypic").length;
		if (imageNum > 1) {
			$("#" + btn_id).attr("src", rootPath + "/statics_wx/images/upload_pic2.png");
		} else {
			$("#" + btn_id).attr("src", rootPath + "/statics_wx/images/upload_pic1.png");
		}
	}

	/**
	 * H5通过ajax提交图片
	 */
	function ajaxFileUpload(obj, type) {
		var id = $(obj).attr("id");
		var check = imageCheck(obj);
		if (!check) {
			return;
		}

		var index = layer.msg('图片上传中...', {
			icon : 16,
			shade : 0.01,
			time : 0
		});

		
		$.ajaxFileUpload({
			url : rootPath + '/uploadFile/uploadOneFile',
			//			url:  rootPath + "/test/upload",
			secureuri : false,
			fileElementId : id, // input标签id属性值
			dataType : 'json',
			success : function(data, status) {
				
				layer.close(index);
				
				if (data.code == 1) {
					var img = "<div class=\"mypic\">" + "<img src=\"" + imgRootURL + data.filePath
							+ "?x-oss-process=image/resize,m_pad,h_60,w_60\" data-src=\"" + imgRootURL + data.filePath
							+ "\" onclick=\"imageView(this);\"/>"
							+ "<a href=\"javascript:void(0)\" class=\"icon_close\"></a>" + "</div>";
					$("#btn_" + type + "_pay").closest("div.upload_picpart").append($(img));
					$("#btn_" + type + "_pay").closest("div.upload_picpart").find("a.icon_close").each(function() {
						$(this).click(function() {
							$(this).closest("div.mypic").remove();
							countImage("btn_" + type + "_pay");
						});
					});
					countImage("btn_" + type + "_pay");
				} else {
					layer.msg(data.msg, {
						time : 1000
					});
				}
			},
			error : function(data, status, e) {
				layer.close(index);
				
				layer.msg('上传图片失败，请重试', {
					time : 1000
				});
			}
		});
	}

	//检查图片格式及大小
	function imageCheck(obj) {
		var id = $(obj).attr("id");
		var filePath = $("#" + id).val();
		//检查后缀
		var ext = filePath.substring(filePath.lastIndexOf("."), filePath.length).toUpperCase();
		if (ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") {
			layer.msg('只能上传图片', {
				time : 500
			});
			return false;
		}
		var file_size = 0;
		if (false || !!document.documentMode) {
			var img = new Image();
			img.src = filepath;
			while (true) {
				if (img.fileSize > 0) {
					if (img.fileSize > 5 * 1024 * 1024) {
						layer.msg('图片不能大于5MB', {
							time : 1000
						});
						return false;
					}
					break;
				}
			}
		} else {
			file_size = obj.files[0].size;
			var size = file_size / 1024;
			if (size > 5120) {
				layer.msg('图片不能大于5MB', {
					time : 1000
				});
				return false;
			}
		}
		return true;
	}
</script>

</head>
<body style="background:#f5f5f5">
<input type="hidden" id="appId" value="${appId }"/>
<input type="hidden" id="timestamp" value="${timestamp }"/>
<input type="hidden" id="nonceStr" value="${nonceStr }"/>
<input type="hidden" id="signature" value="${signature }"/>

<input type="hidden" id="pay_appId" value="${resultMap.appId }"/>
<input type="hidden" id="pay_timeStamp" value="${resultMap.timeStamp }"/>
<input type="hidden" id="pay_nonceStr" value="${resultMap.nonceStr }"/>
<input type="hidden" id="pay_package" value="${resultMap.packageStr }"/>
<input type="hidden" id="pay_paySign" value="${resultMap.paySign }"/>
<input type="hidden" id="pay_signType" value="${resultMap.signType }"/>

<input type="hidden"  id="order_code" value="${orderCode}"/>
<c:set var="rootPath" value="<%=basePath %>"></c:set>
<c:set var="imgRootURL" value="<%=imgRootURL %>"></c:set>
	<div class="yf_info1">
		<p>
			应付款: <b>￥<em><sl:nformat num="${realPayMoney}" type="2" format="#.00"/></em><sl:nformat num="${realPayMoney}" type="3" format="#.00"/>
			</b>
		</p>
	</div>
	<div class="order_info12">
		<div class="hd">
			<h3>
				<span>线下支付</span><i></i>
			</h3>
		</div>
		<div class="bd">
			<div class="zf_way zf_way1">
				<ul>
					<%--对公银行转账 --%>
					<li class="checked">
						<a tag="tag" name="tag_public"></a>
						<label pay_type="<%=OrderConstants.ORDER_PAY_TYPE.PUBLIC_BANK_PAY.getCode() %>" class="checked">
								<div class="xx_1">
									<i></i>
									<div class="txt1">
										<em class="icon1"></em><span>对公转账</span>
									</div>
								</div>
								<div class="bank_list1">
									<div class="bank_list11">
										<dl>
										<c:forEach items="${payAccountList }" var="payAccount" varStatus="status" >
											<c:if test="${payAccount.payType eq '03'}">
												<dt>
													<input type="hidden" id="account_id"  value="${payAccount.id}"/>
													<div class="box16">
														${payAccount.accountName }<br>${payAccount.bankAccount }<br>${payAccount.bankName }<br>${payAccount.bankChild }
													</div>
												</dt>
											</c:if>
										</c:forEach>
										</dl>
									</div>
								</div>
						</label>
						<div class="upload_picpart">
	                    	<div class="mypic">
	                        	<img id="btn_public_pay" src="${rootPath}/statics_wx/images/upload_pic1.png" />
	                        	<div style="display:none">
									<input type="file" name="upload" id="public_pay_upload" accept="image/*" onchange="ajaxFileUpload(this,'public');" />
								</div>
	                        </div>
	                    </div>
					</li>

					<%--对私银行转账 --%>
					<li>
						<a tag="tag" name="tag_private"></a>
						<label pay_type="<%=OrderConstants.ORDER_PAY_TYPE.PRIVATE_BANK_PAY.getCode() %>">
								<div class="xx_1">
									<i></i>
									<div class="txt1">
										<em class="icon2"></em><span>私人银行卡</span>
									</div>
								</div>
								<div class="bank_list1">
									<div class="bank_list11">
										<dl>
											<c:forEach items="${payAccountList }" var="payAccount" varStatus="status" >
												<c:if test="${payAccount.payType eq '04'}">
													<dt>
														<input type="hidden" id="account_id"  value="${payAccount.id}"/>
														<div class="box16">
															${payAccount.accountName }<br>${payAccount.bankAccount }<br>${payAccount.bankName }<br>${payAccount.bankChild }
														</div>
													</dt>
												</c:if>
											</c:forEach>
										</dl>
									</div>
								</div>
						</label>
						<div id="testDiv" class="upload_picpart">
	                    	<div class="mypic">
	                            <img id="btn_private_pay" src="${rootPath}/statics_wx/images/upload_pic1.png" />
	                            <div style="display:none">
									<input type="file" name="upload" id="private_pay_upload" accept="image/*" onchange="ajaxFileUpload(this,'private');" />
								</div>
	                        </div>
	                    </div>
						</li>

				</ul>
			</div>
		</div>

	</div>
	<div class="order_info12">
		<div class="hd">
			<h3>
				<span>线上支付</span><i></i>
			</h3>
		</div>
		<div class="bd">
			<div class="zf_way zf_way3">
				<ul>
					<li>
						<label pay_type="<%=OrderConstants.ORDER_PAY_TYPE.WXPAY.getCode() %>">
							<div class="xx_1">
								<i></i>
								<div class="txt1">
									<em class="icon3"></em><span>微信支付</span>
								</div>
							</div> 
						</label>
					</li>
				</ul>
			</div>
		</div>
	</div>
	<div class="footerfixed3"></div>
	<div class="footer">
		<div class="order_bottom">
			<ul>
				<li></li>
				<li><a href="javascript:void(0)" id="btn_pay" class="btn1">立即支付</a></li>
			</ul>
		</div>
	</div>
</body>
</html>